package cn.edu.imau.zy.student.controller;

import cn.edu.imau.zy.common.annotation.LoginUser;
import cn.edu.imau.zy.common.constant.ConfigConstant;
import cn.edu.imau.zy.common.core.entity.system.SysClasses;
import cn.edu.imau.zy.common.core.entity.system.SysDept;
import cn.edu.imau.zy.common.core.entity.system.SysUser;
import cn.edu.imau.zy.common.log.annotation.OperLog;
import cn.edu.imau.zy.common.log.enums.BusinessType;
import cn.edu.imau.zy.common.utils.StringUtils;
import cn.edu.imau.zy.common.utils.poi.ExcelUtil;
import cn.edu.imau.zy.student.service.IStStudentService;
import cn.edu.imau.zy.system.feign.RemoteClassesService;
import cn.edu.imau.zy.system.feign.RemoteConfigService;
import cn.edu.imau.zy.system.feign.RemoteDeptService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import cn.edu.imau.zy.common.core.domain.R;
import cn.edu.imau.zy.common.core.controller.BaseController;
import cn.edu.imau.zy.common.core.entity.student.StStudent;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 学生信息管理 提供者
 *
 * @author xsc
 * @date 2020-06-18
 */
@RestController
@RequestMapping("student")
public class StStudentController extends BaseController {

    @Autowired
    private IStStudentService stStudentService;
    @Autowired
    private RemoteDeptService deptService;
    @Autowired
    private RemoteClassesService classesService;
    @Autowired
    private RemoteConfigService configService;

    /**
     * 查询${tableComment}
     */
    @GetMapping("get/{studentId}")
    public StStudent get(@PathVariable("studentId") String studentId) {
        return stStudentService.selectStStudentById(studentId);

    }

    /**
     * 获取学生自己的信息
     */
    @GetMapping("get")
    public StStudent get() {
        return stStudentService.selectStStudentById(getCurrentUserId());
    }

    /**
     * 查询学生信息管理列表
     */
    @GetMapping("list")
    public R list(StStudent stStudent, @LoginUser SysUser user) {
        if (user.getRoleIds().contains(1L) || user.getRoleIds().contains(7L)) {
            //管理员 学生处 查看所有
        } else if (user.getRoleIds().contains(6L)) {
            //系领导 查看本系
            stStudent.setDeptId(user.getDeptId());
        } else if (user.getRoleIds().contains(4L)) {
            //班主任 查看本班
            List<SysClasses> clList = classesService.jList();
            List<String> ids = clList.stream().map(p -> p.getClassesId()).collect(Collectors.toList());
            stStudent.getParams().put("classesIds", ids);
        } else {
            return R.error("身份异常");
        }

        startPage();
        return result(stStudentService.selectStStudentList(stStudent));
    }

    /**
     * 查询没有创建帐号的学生列表
     */
    @GetMapping("noLoginList")
    public List<StStudent> getNoLoginList() {
        return stStudentService.getNoLoginList();
    }

    /**
     * 新增保存学生信息管理
     */
    @PostMapping("save")
    public R addSave(@RequestBody StStudent stStudent) {
        stStudent.setStudentId(IdUtil.getSnowflake(2, 2).nextIdStr());
        stStudent.setCreateBy(String.valueOf(getCurrentUserId()));
        return toAjax(stStudentService.insertStStudent(stStudent));
    }

    /**
     * 批量修改学生信息
     */
    @PostMapping("updateBatch")
    public R updateBatch(@RequestBody StStudent stStudent) {
        return toAjax(stStudentService.updateBatch(stStudent));
    }

    /**
     * 批量修改学生信息
     */
    @PostMapping("updateBatchCount")
    public R updateBatchCount(@RequestBody StStudent stStudent) {
        return R.ok(String.valueOf(stStudentService.updateBatchCount(stStudent)));
    }

    /**
     * 修改保存学生信息管理
     */
    @PostMapping("update")
    public R editSave(@RequestBody StStudent stStudent) {
        return toAjax(stStudentService.updateStStudent(stStudent));
    }

    /**
     * 删除${tableComment}
     */
    @PostMapping("remove")
    public R remove(String ids) {
        return toAjax(stStudentService.deleteStStudentByIds(ids));
    }

    /**
     * 学生返校统计 图表
     */
    @PostMapping("atSchoolCount")
    public R atSchoolCount(@RequestBody Map<String, String> params, @LoginUser SysUser user) {
        params.put("grade", configService.selectConfigByKey(ConfigConstant.STUDENT_GRADE_NEW));
        return R.data(stStudentService.atSchoolCount(params));
    }

    /**
     * 导入学生数据
     */
    @OperLog(title = "学生信息", businessType = BusinessType.IMPORT)
    @PostMapping("import")
    @Transactional
    public R importData(@RequestParam("file") MultipartFile file, @LoginUser SysUser user) {
        ExcelUtil<StStudent> util = new ExcelUtil<StStudent>(StStudent.class);
        try {
            Map<String, Long> deptMap = ((List<HashMap>) deptService.listTeachl().get("data"))
                    .stream().map(d -> BeanUtil.mapToBean(d, SysDept.class, false)).collect(Collectors.toList())
                    .stream().collect(Collectors.toMap(SysDept::getDeptName, SysDept::getDeptId));

            //修正数据
            List<StStudent> list = util.importExcel(file.getInputStream());
            list.forEach(student -> {
                student.setStudentId(IdUtil.getSnowflake(1L, 1L).nextIdStr());
                student.setStudentName(StringUtils.replaceBlank(student.getStudentName()));
                student.setIdCard(StringUtils.replaceBlank(student.getIdCard()));
                student.setClassesName(StringUtils.replaceBlank(student.getClassesName()));
                student.setDeptName(StringUtils.replaceBlank(student.getDeptName()));
                student.setSpecialityCode(StringUtils.replaceBlank(student.getSpecialityCode()));
                student.setSpecialityName(StringUtils.replaceBlank(student.getSpecialityName()));
                student.setCreateBy(user.getUserId());
                if (deptMap.get(student.getDeptName()) != null) {
                    student.setDeptId(deptMap.get(student.getDeptName()));
                }
            });
            Map<String, String> classMap = new HashMap<>();
            List<SysClasses> classes = list.stream().map(p -> {
                SysClasses c = new SysClasses();
                c.setClassesName(p.getClassesName());
                c.setDeptName(p.getDeptName());
                c.setDeptId(p.getDeptId());
                c.setGrade(p.getGrade());
                c.setSpecialityCode(p.getSpecialityCode());
                c.setSpecialityName(p.getSpecialityName());
                c.setEducationalLevel(p.getEducationalLevel());
                c.setClassesStatus("1");
                return c;
            }).distinct().collect(Collectors.toList());
            classes.stream().forEach(p -> {
                p.setClassesId(IdUtil.getSnowflake(1L, 1L).nextIdStr());
                classMap.put(p.getClassesName(), p.getClassesId());
            });
            list.stream().forEach(p -> p.setClassesId(classMap.get(p.getClassesName())));
            classesService.saveList(classes);
            stStudentService.insertStStudents(list);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("导入失败");
        }
    }

    @OperLog(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public R export(StStudent student) {
        List<StStudent> list = stStudentService.selectStStudentList(student);
        ExcelUtil<StStudent> util = new ExcelUtil<StStudent>(StStudent.class);
        return util.exportExcel(list, "学生信息表");
    }


}
